<template>
  <div class="weatherBox">
    <div class="iphoneBox">

      <div class="topHeader">
        <div class="timeBox">{{timeValue}}</div>
        <div class="checkCity" @click="handleCheckCity">切换城市</div>
      </div>

      <div class="cityInfo">
        <div class="basicInfo">
          <p class="cityName">{{isNoData(nowWeather.cityName)}}</p>
          <p class="nowWeather">{{isNoData(nowWeather.weather)}}</p>
          <p class="nowAir">{{isNoData(nowWeather.temperature)}}℃</p>
          <p class="nowInfo">
            <span>风力：{{isNoData(nowWeather.windPower)}}级</span>|
            <span>风向：{{isNoData(nowWeather.windDirection)}}</span>|
            <span>空气湿度：{{isNoData(nowWeather.humidity)}}</span>
          </p>
        </div>

        <div class="anyDayWeather">
          <div class="tomorrow" v-for="item of futrueWeather.list.slice(1,4)" :key="item.week">
            <!--  ${item.nightWindPower}级 -->
            {{`${item.dayName}：白天：${item.dayTemp}℃ ${item.dayWeather} ${item.dayWindDir}风 ${item.dayWindPower}级 夜间：${item.nightTemp}℃ ${item.nightWeather} ${item.nightWindDir}风`}}
          </div>
        </div>
      </div>

      <div id="trendChart">

      </div>

      <div :class="['checkCityBox',showCheckBox ? '' : 'showCityBox']">
        <el-cascader clearable size="large" placeholder="请选择地址" style="width: 100%" :options="provinceAndCityData" v-model="addressActive" @change="handleChange" @city="onChangeCity"> </el-cascader>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, reactive, ref,  } from "vue"
import { ElNotification } from 'element-plus'
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import VDistpicker from 'v-distpicker'
import { provinceAndCityData, codeToText } from 'element-china-area-data'

echarts.use([GridComponent, TooltipComponent, LineChart, CanvasRenderer, UniversalTransition]);

let cityInfo = reactive({
  name: '',
  code: null,
})

// 获取时间
let timeValue = ref('')
getNowTime()
let timeID = setInterval(getNowTime,1000)
onUnmounted (()=>{
  clearInterval(timeID) //销毁
})

onMounted(() => {
  // 获取当前地区的IP地址
  AMap.plugin('AMap.CitySearch', function () {
    let citySearch = new AMap.CitySearch()
    citySearch.getLocalCity( async (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        // 查询成功，result即为当前所在城市信息
        console.log(result, '位置信息')
        cityInfo.name = result.city
        cityInfo.code = result.adcode
        await getNowDayWeather(result.adcode)
      }
    })
  })
})

let nowWeather = reactive({
  cityName: '', // 城市名称
  weather: '',  // 天气
  temperature: '',  // 温度
  windPower: '',  // 风力
  windDirection: '',  // 风向
  humidity: '',  // 空气湿度
})

let futrueWeather = reactive({
  list: [],
  temperList: []
})

// 获取天气
function getNowDayWeather(code){
  //加载天气查询插件
  AMap.plugin('AMap.Weather', function() {
    //创建天气查询实例
    let weather = new AMap.Weather()

    //执行实时天气信息查询
    weather.getLive(code, function(err, data) {
      // console.log(err, data, '当天天气')
      if(err !== null){
        ElNotification({
          title: '提示',
          message: '获取当前天气失败，请刷新重试。',
        })
        nowWeather.cityName = data.city
        nowWeather.weather = data.weather
        nowWeather.temperature = data.temperature
        nowWeather.windPower = data.windPower
        nowWeather.windDirection = data.windDirection
        nowWeather.humidity = data.humidity
        return false
      }
      nowWeather.cityName = data.city
      nowWeather.weather = data.weather
      nowWeather.temperature = data.temperature
      nowWeather.windPower = data.windPower
      nowWeather.windDirection = data.windDirection
      nowWeather.humidity = data.humidity
    })

    // 查询未来三天天气
    weather.getForecast(code, function(err, data) {
      console.log(err, data, '未来三天天气')
      if(err !== null){
        ElNotification({
          title: '提示',
          message: '获取当前天气失败，请刷新重试。',
        })
        return false
      }
      futrueWeather.list = data.forecasts
      futrueWeather.temperList = []

      futrueWeather.list.map(item => {
        // item.dayName = comWeekName(item.week)
        let date = item.date.split('-')
        item.dayName = `${date[1]}月${date[2]}日`
        futrueWeather.temperList.push(item.dayTemp)
      })

      draw()
    })
  })
}

// 绘制图表
function draw(){
  if(document.getElementById('trendChart') == null){
    return false
  }
  echarts.dispose(document.getElementById('trendChart'))
  let myChart = echarts.init(document.getElementById('trendChart'))
  myChart.setOption({
    xAxis: {
      type: 'category',
      data: ['今天', '明天', '后天', '大后天'],
      axisLine: {
        lineStyle: {
            color: "#fff",
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
            color: "#fff",
        }
      },
      axisLabel: {
        formatter: '{value} °C'
      }
    },
    tooltip: {
      show: true,	
    },
    series: [
      {
        data: futrueWeather.temperList,
        type: 'line',
        itemStyle:{
          normal:{
            label:{
              show:true, //在每个上面显示当前值
              formatter:function(data){
                return data.value + '°C'
              }
            }
          }
        },
      }
    ],
  })
}

let showCheckBox = ref(false)

function handleCheckCity(){
  showCheckBox.value = !showCheckBox.value
}
let addressActive = ref('')
function handleChange(value){
  console.log(codeToText[value[1]])
  getNowDayWeather(codeToText[value[1]])
  showCheckBox.value = false
}

function onChangeCity(value){
  console.log(value)
}


  // 工具函数
// 判断值是否为空 
function isNoData(value){
  return value ?  value : '--'
}

// 重命名星期时间
function comWeekName(value){
  switch(value){
    case '1':
      return '星期一'
      break;
    case '2':
      return '星期二'
      break;
    case '3':
      return '星期三'
      break;
    case '4':
      return '星期四'
      break;
    case '5':
      return '星期五'
      break;
    case '6':
      return '星期六'
      break;
    case '7':
      return '星期日'
      break;
    default: 
      return '--'
  }
}

// 获取当前时间
function getNowTime(){
  let nowTime = new Date()
  let nowHour = nowTime.getHours()
  let nowMinutes = nowTime.getMinutes() < 10 ? `0${nowTime.getMinutes()}` : nowTime.getMinutes() 
  timeValue.value = `${nowHour}: ${nowMinutes}`
}

</script>

<style lang="less" scoped>
.weatherBox{
  width: 100%;
  height: 90vh;

  .iphoneBox{
    position: relative;
    overflow: hidden;
    width: 400px;
    height: 667px;
    background-color: #4c4c4c;
    margin: 20px auto 0;
    border-radius: 15px;
    color: #fff;

    .topHeader{
      display: flex;
      padding: 0 10px;
      justify-content: space-between;
      line-height: 34px;
      height: 34px;
      font-size: 13px;

      .checkCity{
        cursor: pointer;
      }
    }

    .cityInfo{

      .basicInfo{

        .nowWeather{
          font-size: 14px;
        }

        .nowAir{
          font-size: 32px;
          font-weight: 700;
        }
      }

      .anyDayWeather{
        margin-top: 30px;
        div{
          font-size: 12px;
          width: 85%;
          margin: 5px auto;
          line-height: 46px;
          background-color: rgba(255, 255, 255, .3);
          border-radius: 5px;
          color: #dbdce0;
          text-align: left;
          padding: 0 0 0 5px;
        }
      }
    }

    .checkCityBox{
      width: 100%;
      height: 40vh;
      background-color: rgba(255, 255, 255, .2);
      position: absolute;
      left: 0px;
      bottom: 0px;
      transition: height 1s;
    }

    .showCityBox{
      height: 0vh;
    }

    ::v-deep(.el-cascader){
      width: 90% !important;
    }
  }
}

#trendChart{
  width: 100%;
  height: 40vh;
  padding: 0 10px;
}
</style>
